package com.distributer.delayqueue.zookeeper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.leader.LeaderLatch;
import org.apache.curator.framework.recipes.leader.LeaderLatchListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.distributer.delayqueue.autoconfigure.RegistryProperties;


public class SimpleLeaderManager extends LeaderManager{

	private static final Logger LOGGER = LoggerFactory.getLogger(SimpleLeaderManager.class);
	
	private LeaderLatch leaderLatch;
	
	private CuratorFramework curatorFramework;
	
	private List<LeaderLatchListener> latchListeners = new ArrayList<LeaderLatchListener>();
	
	private AtomicBoolean isLatch = new AtomicBoolean(false);

	private String serviceName;
		
	private RegistryProperties registerProperties;
	
	public void init(){
		CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder()
				.connectString(registerProperties.getServerList())
				.namespace(registerProperties.getNamespace())
				.retryPolicy(new ExponentialBackoffRetry(registerProperties.getBaseSleepTimeMilliseconds(), 
						registerProperties.getMaxRetries(), 
						registerProperties.getMaxSleepTimeMilliseconds()));
		curatorFramework = builder.build();
		curatorFramework.start();
		leaderLatch = new LeaderLatch(curatorFramework, ServerNode.LEADERLATCH, serviceName, LeaderLatch.CloseMode.NOTIFY_LEADER);
		for (LeaderLatchListener leaderLatchListener : latchListeners) {
			leaderLatch.addListener(leaderLatchListener);
		}
		start();
		LOGGER.info("finished started zookeeper....");
	}
	
	
	
	@Override
	public void start() {
		//启动监听
		if (isLatch.compareAndSet(false, true)) {
			try {
				leaderLatch.start();
				LOGGER.info("started latch...");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void stop() {
		if (isLatch.compareAndSet(true, false)) {
			try {
				leaderLatch.close();
				LOGGER.info("stopped latch...");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public boolean isRunning() {
		return isLatch.get();
	}

	@Override
	public boolean isLeader() {
		return leaderLatch.hasLeadership();
	}
	
	public void setServiceName(String serviceName) {
		this.serviceName = serviceName;
	}
	
	public void setRegisterProperties(RegistryProperties registerProperties) {
		this.registerProperties = registerProperties;
	}
	
	public void addListener(LeaderLatchListener leaderLatchListener){
		this.latchListeners.add(leaderLatchListener);
	}

}
